<template>
	<view>
		<view class="h2">学生列表</view>
		<view class="table">
			<checkbox-group @change="handleCheck">
				<view class="table-item" v-for="item in computedList" :key="item.id">
					<view>
						<checkbox :value="item.id" :checked="isChecked(item.id)"></checkbox>
						姓名：{{item.name}}
					</view>
					<view>
						性别：{{item.sex}}
					</view>
					<view>
						电话号码：{{item.tel}}
					</view>
					<view>
						专业：{{item.major}}
					</view>
					<button @click="handleDeleteRow(item.id)" type="warn" size="mini">删除</button>
				</view>
			</checkbox-group>
		</view>
		<view class="foot">
			<view class="view-type">{{ }}未选</view>
			<view @click="handleType(1)" :class="getClass(1)">全部</view>
			<view @click="handleType(2)" :class="getClass(2)">未选中</view>
			<view @click="handleType(3)" :class="getClass(3)">选中</view>
			<view @click="handleDelete" class="view-type">删除选中</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		ref,
		computed
	} from "vue";
	const selectIds = ref([]);
	const type = ref(1);

	const props = defineProps({
		listData: {
			type: Array,
			required: true,
		},
	});

	const emits = defineEmits(["delete-row"]);

	function handleCheck(v) {
		selectIds.value = v.detail.value;
	}

	function handleDeleteRow(v: number) {
		// 触发自定义事件，让父组件完成删除
		emits("delete-row", v);

		// 把存储选中项的也删除
		const index = selectIds.value.findIndex((v) => v == id);
		if (index != -1) {
			selectIds.value.splice(index, 1);
		}
	}

	function handleDelete() {
		// 触发自定义事件，让父组件完成删除
		emits("delete", selectIds.value);

		// 把selectIds也清空
		selectIds.value.length = 0;
	}

	function isChecked(id: number) {
		// forEach
		// 结果是数组：map（有原有成员创建新成员） filter（筛选新成员）
		// 结果是boolean：some（也有没有通过测试的成员）,every（是否所有成员都通过测试）
		// 查找：find（查找成员）,findIndex（查找index）
		return selectIds.value.some(v => v == id);
	}

	function getClass(value: number) {
		return {
			// 当对象的属性值为true的时候，表示有该属性名的class值
			"span-type-active": type.value == value,
			"span-type": true,
		};
	}

	function handleType(v: number) {
		type.value = v;
	}

	const computedList = computed(() => {
		// console.log("selectIds = ",selectIds);
		switch (type.value) {
			// 选中
			case 3: {

				return props.listData.filter(
					(v1: any) => selectIds.value.findIndex((v2) => v2 == v1.id) != -1
				);
			}
			// 未选中
			case 2: {
				return props.listData.filter(
					(v1: any) => selectIds.value.findIndex((v2) => v2 == v1.id) == -1
				);
			}
			default:
				return props.listData;
		}
	});
</script>

<style lang="scss" scoped>
	.table-item {
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx 0rpx;
		border-bottom: 1rpx solid #8f8f8f;

		view {
			width: 50%;
			padding: 5rpx 0rpx
		}
	}

	.foot {
		display: flex;
		justify-content: space-between;
		padding: 5rpx 0rpx;

		.span-type {
			padding: 10rpx;

		}

		.span-type-active {
			color: #fff;
			background-color: #ac1111;
		}
	}
</style>
